<?php

namespace App\Repositories;
//在 Laravel 5 中使用 Repository 模式实现业务逻辑和数据访问的分离
use App\Models\Category;
use App\Models\Article;
use Carbon\Carbon;
use App\Tools\Markdowner;
use Auth;

class ArticleRepository extends BaseRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Article::class;
    }

    public function filterData(array &$data)
    {
        if (!$data['cover']) {
            $fileName = mt_rand(1, 299);
            $data['cover'] = 'http://pi88z466o.bkt.clouddn.com/article/random/' . $fileName . '.jpg';
        }

        if (!isset($data['published_at'])) {
            $data['published_at'] = Carbon::now();
        }
        $data['is_draft'] = isset($data['is_draft']);
        $data['is_original'] = isset($data['is_original']);

        $content = [
            'raw' => $data['content'],
            'html' => (new Markdowner())->convertMarkdownToHtml($data['content']),
        ];
        $data['content'] = json_encode($content);
        $data['user_id'] = \Auth::id();
        $data['last_user_id'] = \Auth::id();
    }

    public function preCreate(array &$data)
    {
        $this->filterData($data);
//        dd($data);
        $data['slug'] = $this->model->generateSlug($data['title']);
        return $data;
    }

    public function created(&$data, $article)
    {
        $this->updateOrCreateArticleContent($article, $data);
        $this->addTags($article, $data);
    }

    public function preUpdate(array &$data, $article)
    {
        $data = $this->filterData($data);
        if (isset($data['title']) && $article->title != $data['title']) {
            $data['slug'] = $this->model->generateSlug($data['title']);
        }

        return $data;
    }

    public function updated(&$data, $article)
    {
        $this->updateOrCreateArticleContent($article, $data);
        $this->syncTags($article, $data);
    }

    /**
     * 更新或创建文章正文
     * @param Article $article
     * @param $content
     */
    private function updateOrCreateArticleContent(Article $article, &$data)
    {
        if (isset($data['content'])) {
            $article->articleContent()->updateOrCreate(
                [], [
                    'content' => $data['content']
                ]
            );
        }
    }

    /**
     * 添加标签
     * @param Article $article
     * @param $data
     */
    private function addTags(Article $article, &$data)
    {
        if (isset($data['tag_ids'])) {
            $article->tags()->attach($data['tag_ids']);
        }
    }

    /**
     * 同步标签
     * @param Article $article
     * @param $data
     */
    private function syncTags(Article $article, &$data)
    {
        if (isset($data['tag_ids'])) {
            $article->tags()->sync($data['tag_ids']);
        }
    }

}
